package org.eclipse.wtp.puzzled;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PuzzledServlet extends HttpServlet implements Servlet {
	MySQLAccess dbo;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MsgList msgs = new MsgList();
		try {
			dbo = new MySQLAccess();
		} catch (Exception e) {
			System.err.println(e);
		}
		String todo = request.getParameter("todo");
		if (todo.equals("load")) {
			SudokuGenerator puzzle = new SudokuGenerator(9);
			System.out.println("Creating sudoku");
			request.getSession().setAttribute("puzzle", puzzle);
		} else if (todo.equals("logout")) {
			msgs.addMsg("Logged out", Msg.SUCCESS);
			request.getSession().setAttribute("user", null);
		} else if (todo.equals("login") || todo.equals("register") || todo.equals("index")) {
			String path = "/" + todo + ".jsp";
			request.getSession().setAttribute("msgs", new MsgList());
			getServletContext().getRequestDispatcher(path).forward(request, response);
		} else if (todo.equals("scores")) {
			try {
				String path = "/" + todo + ".jsp";
				request.getSession().setAttribute("scores", dbo.getHighScores());
				request.getSession().setAttribute("msgs", new MsgList());
				getServletContext().getRequestDispatcher(path).forward(request, response);	
			} catch (Exception e) {
				System.err.println(e);
			}
		}
		if (!todo.equals("login") && !todo.equals("register") && !todo.equals("index") && !todo.equals("scores")) {
			request.getSession().setAttribute("msgs", msgs);
			getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MsgList msgs = new MsgList();
		String togo = "/index.jsp";
		try {
			dbo = new MySQLAccess();
		} catch (Exception e) {
			System.err.println(e);
		}
		String todo = request.getParameter("todo");
		request.getSession().setAttribute("solved", false);
		if (todo.equals("new")) {
			int level = Integer.parseInt(request.getParameter("level"));
			Sudoku puzzle = new Sudoku(level);
			request.getSession().setAttribute("level", level);
			request.getSession().setAttribute("puzzle", puzzle);
		} else if (todo.equals("select")) {
			Sudoku puzzle = (Sudoku) request.getSession().getAttribute("puzzle");
			int x = Integer.parseInt(request.getParameter("x"));
			int y = Integer.parseInt(request.getParameter("y"));
			puzzle.selectCell(x,y);
			request.getSession().setAttribute("puzzle", puzzle);
		} else if (todo.equals("solve")) {
			Sudoku puzzle = (Sudoku) request.getSession().getAttribute("puzzle");
			puzzle.solve();
			request.getSession().setAttribute("solved", true);
			request.getSession().setAttribute("puzzle", puzzle);
			User u = (User)request.getSession().getAttribute("user");
			if (u != null) {
				int newPoints = puzzle.numCorrect();
				newPoints += u.getPoints();
				u.setPoints(newPoints);
				try {
					dbo.updatePoints(u.getUserName(), newPoints);
				} catch (Exception e) {
					System.err.println(e);
				}
			}
		} else if (todo.equals("hint")) {
			Sudoku puzzle = (Sudoku) request.getSession().getAttribute("puzzle");
			puzzle.hint();
			if (puzzle.numHints() == puzzle.numOrigUserInput()) {
				puzzle.solve();
				request.getSession().setAttribute("solved", true);
			}
			
			request.getSession().setAttribute("puzzle", puzzle);
		} else if (todo.equals("login")) {
			String user = request.getParameter("username");
			String pass = request.getParameter("password");
			boolean flag = true;
			togo = "/login.jsp";
			if (user.equals("")) {
				flag = false;
				msgs.addMsg("Please provide a username", Msg.ERROR);
			}
			if (pass.equals("")) {
				flag = false;
				msgs.addMsg("Please provide a password", Msg.ERROR);
			}
			
			if (flag) {
				try {
					User u = dbo.authenticate(user, pass);
					request.getSession().setAttribute("user", u);
					if (u != null) {
						togo = "/index.jsp";
						msgs.addMsg("Logged in", Msg.SUCCESS);
					} else
						msgs.addMsg("Incorrect password", Msg.ERROR);
				} catch (Exception e) {
					msgs.addMsg("Username does not exist", Msg.ERROR);
					System.err.println(e);
				}
			}
		} else if (todo.equals("register")) {
			String fname = request.getParameter("firstname");
			String lname = request.getParameter("lastname");
			String email = request.getParameter("email");
			String user = request.getParameter("username");
			String pass = request.getParameter("password");
			String conf = request.getParameter("confirm");
			boolean flag = true;
			if (fname.equals("")) {
				flag = false;
				msgs.addMsg("Please provide your firstname", Msg.ERROR);
			}
			if (lname.equals("")) {
				flag = false;
				msgs.addMsg("Please provide your lastname", Msg.ERROR);
			}
			if (email.equals("")) {
				flag = false;
				msgs.addMsg("Please provide your email", Msg.ERROR);
			}
			if (user.equals("")) {
				flag = false;
				msgs.addMsg("Please provide a username", Msg.ERROR);
			}
			if (pass.equals("")) {
				flag = false;
				msgs.addMsg("Please provide a password", Msg.ERROR);
			}
			if (conf.equals("")) {
				flag = false;
				msgs.addMsg("Please confirm your password", Msg.ERROR);
			}
			if (!pass.equals(conf)) {
				flag = false;
				msgs.addMsg("Passwords do not match", Msg.ERROR);
			}
			togo = "/register.jsp";
			if (flag) {
				try {
					User newUser = dbo.createUser(fname, lname, email, user, pass);
						togo = "/login.jsp";
						msgs.addMsg("Registered! You can login now!", Msg.SUCCESS);
					
				} catch (Exception e) {
					msgs.addMsg("Username already exists", Msg.ERROR);
					System.err.println(e);
				}
			}
		}
		request.getSession().setAttribute("msgs", msgs);
		if (todo.equals("login") || todo.equals("register"))
			getServletContext().getRequestDispatcher(togo).forward(request, response);
		else
			getServletContext().getRequestDispatcher("/puzzle.jsp").forward(request, response);
	}

}
